//microcommand define zids
const IDC = {
  LR: "⿰",
  LL: "⿲",
  UD: "⿱",
  UU: "⿳",
  RD: "⿸",
  RU: "⿺",
  LD: "⿹",
  LU: "⿽",
  OD: "⿵",
  OR: "⿷",
  OU: "⿶",
  OL: "⿼",
  OC: "⿴",
  XX: "⿻",
  MI: "⿾",
  RO: "⿿",
  SU: "㇯",
}
const idcAliasRE = new RegExp(Object.keys(IDC).join("|"), "ig")
function isIDS(str) {
  str = str.replace(idcAliasRE, a => IDC[a.toUpperCase()])
  let counter = 1
  for (const [i, c] of Object.entries([...str])) {
    if ("⿰⿱⿸⿺⿹⿽⿵⿷⿶⿼⿴⿻㇯".includes(c)) {
      counter += 1
    } else if ("⿲⿳".includes(c)) {
      counter += 2
    } else if ("⿾⿿".includes(c)) {
      // do nothing
    } else {
      if (i === 0 || --counter < 0) return false
    }
  }
  return counter === 0
}
ctx.$commander.domain("zids-ids", content => {
  content = h.unescape(content)
  if (!isIDS(content)) throw new RangeError
  return content
})
inject(["puppeteer"])
signature("<ids:zids-ids>", { checkArgCount: true, strictOptions: true })
action(async ({ session }, ids) => {
  const p = await ctx.puppeteer.page()
  try {
    await p.goto("https://zi.tools/?secondary=ids&seq=" + encodeURIComponent(ids))
    await p.waitForNetworkIdle()
    await p.waitForSelector(".stretch-center.pc-only+div>div:not([set='loading'])")
    let e = await p.$eval("#zusvgimgkage", e => e.outerHTML).catch(() => null)
    let clip = null
    if (!e) {
      const s = await p.click(".fixedSecondaryHeader a>span[style*='font-size:33px']").then(() => true, () => false)
      if (s) {
        await p.waitForSelector(".left_row_column_1")
        e = await p.$eval("#zitouSvg", e => e.outerHTML).catch(() => null)
      } else {
        clip = (await p.$(".stretch-center.pc-only+div>div"))?.boundingBox()
      }
    }
    if (e) {
      await p.setContent(e)
      clip = await (await p.$("svg")).boundingBox()
    }
    return h.image(await p.screenshot({ clip }), "image/png")
  } finally {
    p.close()
  }
})
locale("zh-CN", { description: "用字统网组字", usage: "若给定的序列可统合到已入U的汉字，则会转而对该字的信息截图返回。" })